package structuralPattern.flyweight.example01;

import java.util.HashMap;
import java.util.Map;

/**
 * 享元工厂类
 *      作用：作为存储享元对象的享元池，用户获取享元对象时先从享元池获取，
 *          没有就创建新的，存入享元池
 */
public class FlyweightFactory {

    // map 享元池
    private Map<String,Flyweight> pool = new HashMap<>();

    // 构造方法
    // 实现享元对象之间传递状态
    public FlyweightFactory() {
        // 添加对应的内部状态
        pool.put("A",new ConcreteFlyweight("A"));
        pool.put("B",new ConcreteFlyweight("B"));
        pool.put("C",new ConcreteFlyweight("C"));
    }

    // 根据内部状态查找享元对象
    public Flyweight getFlyweight(String key){
        // 对象是否存在
        if (pool.containsKey(key)){
            System.out.println("===== 享元池中存在，直接复用，key：" + key);
        }else {
            System.out.println("===== 享元池中不存在，创建新的");
            pool.put(key,new ConcreteFlyweight(key));
        }

        return pool.get(key);
    }
}
